package de.grosjohann.android.feuerwehr;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import de.grosjohann.android.feuerwehr.adapter.FahrzeugListAdapter;
import de.grosjohann.android.feuerwehr.domain.Fahrzeug;
import de.grosjohann.android.feuerwehr.fms.FMSAuthService;
import de.grosjohann.android.feuerwehr.fms.FMSService;
import de.grosjohann.android.feuerwehr.fms.FMSServiceFacade;
import de.grosjohann.android.feuerwehr.panel.Panel;
import de.grosjohann.android.feuerwehr.util.JSON2ObjectUtil;

public class MainActivity
  extends Activity {

  public static final String FMS_OBJECT = "feuerwehr.OBJECT";

  private static final String NAME = "MainActivity";

  private boolean authorized = false;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    ListView lv = (ListView) findViewById(R.id.lvFMS);
    BaseAdapter baseAdapter = new FahrzeugListAdapter(this, R.layout.fahrzeug);
    lv.setAdapter(baseAdapter);

    lv.setTextFilterEnabled(true);

    lv.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // When clicked, clear Notification
        Fahrzeug obj = ((FahrzeugListAdapter) parent.getAdapter()).getItem(position);

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancel(FMSService.FMS_SERVICE_NOTIFICATION_ID);

        // if authorized, show FMSStatus-Dialog
        if (authorized) {
          Intent li = new Intent(MainActivity.this, StatusActivity.class);
          li.putExtra(FMS_OBJECT, obj);
          startActivity(li);
        }
      }
    });

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
      Log.i("MainActivity", "started - has extras");
      updateFMSList((String) extras.get(FMSService.FMS_STATUS_DATA));
    }

    // Setting for FMSService
    FMSService.updateUIListener = new IUpdateUIListener() {
      @Override
      public void updateUI(final String newData) {
        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            updateFMSList(newData);
          }
        });
      }

      @Override
      public void showInfo(final String info) {
        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            Panel panel = new Panel(getApplicationContext(), MainActivity.this);
            panel.showInfo(info);
          }
        });
      }

      @Override
      public void showWarning(final String warning) {
        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            Panel panel = new Panel(getApplicationContext(), MainActivity.this);
            panel.showWarning(warning);
          }
        });
      }

      @Override
      public void showError(final String error) {
        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            Panel panel = new Panel(getApplicationContext(), MainActivity.this);
            panel.showError(error);
          }
        });
      }
    };

    // Start FMSService
    FMSServiceFacade.restartRepeating(this);

    // Settings for FMSAuthService
    FMSAuthService.updateUIListener = new IUpdateUIListener() {
      @Override
      public void updateUI(String data) {
        try {
          JSONObject jsonObj = new JSONObject(data);
          TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
          MainActivity.this.authorized = jsonObj.getBoolean(tm.getDeviceId());
        } catch (JSONException ex) {
          Log.e(NAME, ex.getMessage());
        }
      }

      @Override
      public void showInfo(String info) {
        // nothing to do        
      }

      @Override
      public void showWarning(String warning) {
        // nothing to do        
      }

      @Override
      public void showError(String error) {
        // nothing to do        
      }
    };

    // Start FMSAuthService once
    TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    FMSServiceFacade.getAuthorization(this, tm.getDeviceId());
  }

  @Override
  protected void onResume() {
    super.onResume();

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.cancel(FMSService.FMS_SERVICE_NOTIFICATION_ID);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
      case R.id.miPrefs:
        startActivity(new Intent(this, PrefsActivity.class));
        return true;
      case R.id.miInfo:
        startActivity(new Intent(this, InfoActivity.class));
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  @Override
  protected Dialog onCreateDialog(int id) {
    return (new AlertDialog.Builder(MainActivity.this)).setIcon(R.drawable.dlg_error).setTitle(R.string.lblError)
        .setMessage(R.string.errReceiveFMSData)
        .setPositiveButton(R.string.lblOk, new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton) {
            /* Only close the dialog. */
          }
        }).create();
  }

  /*
   * Update of FMSData.
   */
  private void updateFMSList(String newData) {
    try {
      ListView lv = (ListView) findViewById(R.id.lvFMS);
      ((FahrzeugListAdapter) lv.getAdapter()).addAll(JSON2ObjectUtil.getFahrzeugList(newData));

      TextView tvNoStatus = (TextView) findViewById(R.id.tvNoStatus);
      tvNoStatus.setVisibility(View.GONE);
    } catch (JSONException ex) {
      Log.e(NAME, ex.getMessage(), ex);

      Panel panel = new Panel(getApplicationContext(), this);
      panel.showError(R.string.errReceiveFMSData);
    }
  }

}
